#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2020/9/18 15:27
# @File    : test.py
# @Author  : 
# @Email   : 
# @remark  :测试用


import setting

#
# 测试数据库连接
#

from CommonModule import OperaMssql

# TODO：从数据加中取部门ID列表
ms = OperaMssql.MSSQL(host=setting.DB[setting.DB_CURRENT][0],
                      port=setting.DB[setting.DB_CURRENT][1],
                      user=setting.DB[setting.DB_CURRENT][2],
                      pwd=setting.DB[setting.DB_CURRENT][3],
                      db=setting.DB[setting.DB_CURRENT][4])
# conn = ms.GetConnect()
# print(conn)

strSql = 'select ding_id FROM department_info WHERE status=1'

departmentList = ms.ExecQuery(strSql)

# print(departmentList)

# str='insert into department_info (ding_id, ding_upper_id,status,name) values ({0},{1},{2},{3})'.format('2','3',0,'132')

# str = 'UPDATE department_info SET ding_upper_id = {0}, status = {1},name = {2} WHERE ding_id = {3}'.format(3,1,1,3)
#
# ms.ExecSql(str)

# from CommonModule import NumberGeneration
#
# t = NumberGeneration.now_time_conversion_code()
# print(t)
#
# a=NumberGeneration.code_conversion_time(t)
# print(a)


import requests

# TODO:取access_token
url = 'https://oapi.dingtalk.com/gettoken'
params = {
    'appkey': setting.DINGTALK['AppKey'],
    'appsecret': setting.DINGTALK['AppSecret']
}
res = requests.get(url=url, params=params)
# print(res.text)
# print(res.json())
# print(res.json()['access_token'])
# TODO：取用户ID列表
userList = []
url = 'https://oapi.dingtalk.com/user/getDeptMember'
for deptId in departmentList:
    params = {
        'access_token': res.json()['access_token'],
        'deptId': deptId
    }
    res2 = requests.get(url=url, params=params)
    setting.DingSleep()
    # print(res2.text)
    # print(res2.json()['userIds'])
    userList.extend(res2.json()['userIds'])
# print(userList)
# 删除列表中重复项
userList = list(dict.fromkeys(userList))
# print(userList)

# TODO：取用户信息
dingUserInfoList = []
userInfo = []
url = 'https://oapi.dingtalk.com/user/get'
for user_id in userList:
    params = {
        'access_token': res.json()['access_token'],
        'userid': user_id
    }
    res3 = requests.get(url=url, params=params)
    setting.DingSleep()
    # print(res3.text)
    userInfo.append(res3.json()['userid'])
    userInfo.append(res3.json()['department'])
    userInfo.append(res3.json()['name'])
    dingUserInfoList.append(userInfo)
    userInfo = []

# print(dingUserInfoList)

# TODO:写入数据库

# 设置所有人员状态为0
strSql = 'UPDATE person_info set status=0'
ms.ExecSql(strSql)

# 取用户表中所有数据
strSql = 'select ding_id from person_info'
dbUserList = ms.ExecQuery(strSql)
# print(dbUserList)
# print(len(dbUserList))
# print(dbUserList[2][0])
#
# print(userInfoList)
# print(len(userInfoList))
# print(type(userInfoList[0][1]))
#
# list1=[str(userDepartmentList) for userDepartmentList in userInfoList[0][1]]
# print(list1)


# 对比数据后写入
i = j = 0
sqlList = []
while (i < len(dingUserInfoList)):
    k = False
    while (j < len(dbUserList)):
        tempA=int(dbUserList[j][0])
        tempB=int(dingUserInfoList[i][0])
        if (tempA == tempB):
            k = True
            break
        j += 1
    # 把列表中的INT改为字符串
    temp1 = [str(t) for t in dingUserInfoList[i][1]]
    tempDepartmentList = ",".join(temp1)

    if (k):
        strSql = "UPDATE person_info SET department_list_id = '{0}',name = '{1}', status = 1 WHERE ding_id = '{2}'".format(
            tempDepartmentList, dingUserInfoList[i][2], dingUserInfoList[i][0])
    else:
        strSql = "insert into person_info (ding_id,department_list_id,name,status)values('{0}','{1}','{2}',1)".format(
            dingUserInfoList[i][0], tempDepartmentList, dingUserInfoList[i][2])
    j = 0
    i += 1
    sqlList.append(strSql)
print(sqlList)

ms.ExecSqlList(sqlList)


# import requests
#
# url = 'https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token=2cd3afa0b18233b8b1049d1fdafd7c09'
# data = {'status_list': '2,3,5,-1','offset':0,'size':50}
# r = requests.post(url, data)
# print(r)
# print(r.text)
# print(r.content)
